<template>
  <view class="container">
    <!-- 提交表单 -->
    <u-form v-show="model === 1" :model="form" ref="uForm">
      <u-form-item label="身份证姓名" label-width="180" prop="idCardName" required
      >
        <u-input v-model="form.idCardName" placeholder=""
        />
      </u-form-item>
      <u-form-item label="身份证号码" label-width="180" prop="idCardNo" required
      >
        <u-input v-model="form.idCardNo" placeholder=""
        />
      </u-form-item>
      <u-form-item label="从事工作" label-width="180" prop="job" required>
        <u-input
            v-model="form.job"
            type="select"
            :select-open="showJobSel"
            @click="showJobSel = true"
            placeholder="请选择从事工作"
        />
        <u-select v-model="showJobSel" :list="jobList" @confirm="selJob"></u-select>
      </u-form-item>
      <u-form-item label="入职日期" label-width="180" prop="inductionDate" required
      >
        <u-input v-model="form.inductionDate" placeholder=""
        />
      </u-form-item>

      <u-button type="primary" shape="square" :ripple="true" size="default" @click="submit"
                :disabled="disabledBtn"
      >{{ btnText }}
      </u-button
      >

    </u-form>

    <!-- PDF显示 -->
    <view v-if="model === 2" class="pdf-wrapper1">
      <text class="loading-box" v-if="isShowLoading">
        <u-loading mode="circle" size="150" color="#2b85e4"></u-loading>
        <view class="text">协议生成中，请稍后···</view>
      </text>

      <view class="pdf-box" :class="{ h80: !isSign }">
        <show-pdf class="iframe" ref="pdf" v-for="i in numPages" :key="i" :src="url" :page="i"></show-pdf>
      </view>

      <text v-if="!isSign" class="fixed">
        <text class="tips">提示：手指上下滑动查看更多内容。</text>
        <u-button type="primary" shape="square" :ripple="true" size="medium" class="custom-btn" @click="goSign"
        >前往签名
        </u-button
        >
      </text
      >
    </view>

    <!-- 签名 -->
    <view v-show="model=== 3" class="sign-wrapper">
      <signature :showCanvas="showCanvas" @finish="onSignFinish"></signature>
    </view>

  </view>
</template>

<script>
import signature from "@/components/signature.vue";
import * as consts from "@/utils/constant.js";
import ShowPdf from "vue-pdf";
import {mapGetters} from "vuex"
import AuthInfo from "@/utils/authInfo.js";
import axios from "axios";
import reportApi from '@/api/modules/report'

export default {
  data() {
    return {
      isShowLoading: true,
      url: "",
      preUrl: '',
      numPages: null, // pdf 总页数,
      form: {
        idCardName: '',
        idCardNo: '',
        inductionDate: null,
        job: null,
      },
      disabledBtn: false,
      btnText: '签署弃保证明',
      showJobSel: false,
      jobList: [
        {
          value: '优选工作',
          label: '优选工作'
        },
      ],
      rules: {
        job: [
          {
            required: true,
            message: "请选择从事工作",
            trigger: "change",
          },
        ],
      },
      model: 1,
      //打开canvas绘制签名
      showCanvas: true,
    };
  },
  components: {
    ShowPdf,
    signature,
  },
  computed: {
    ...mapGetters(["isSign"]),
  },
  async onShow() {
    await this.getInduction()
  },
  methods: {
    selJob(e) {
      this.form.job = e[0].label
    },
    async getInduction() {
      try {
        this.form = {
          idCardName: '',
          idCardNo: '',
          inductionDate: null,
          job: null,
        }
        const {data, msg} = await this.$api.riders.getInduction()
        if (!data) {
          if (msg === '不存在微信用户记录') {
            // 跳转到简单登录页注册微信记录
            this.$store.commit("UPDATE_ROUTEURL", "/pages/simple_login/index");
            return
          }
          this.btnText = '未有过入职记录,无法签署弃保申请'
          this.disabledBtn = true
          uni.showToast({
            title: '未有过入职记录,无法办理弃保',
            icon: "error",
          });
          return
        }
        this.form = {...data}
        this.form.job = this.jobList[0].value
        this.btnText = '签署弃保证明'
        this.disabledBtn = false
      } catch (e) {
        uni.showToast({
          title: '查询入职状态错误' + e,
          icon: "error",
        });
        this.btnText = '查询入职状态错误' + e
        this.disabledBtn = true
        let text = '弃保申请查询入职状态错误 ' + ' \n '
        text += ` ex: ${e}  \n `
        text += ` stack: ${e.stack} \n`
        await reportApi.errorReport({error: text, appId: '', openId: '',});
      }

    },
    async submit() {
      this.$refs.uForm.validate(async valid => {
        if (!valid) {
          return
        }
        try {
          const res = await this.$api.riders.insureCancel(this.form)
          await this.getPdf(res)
        } catch (e) {
          uni.showToast({
            title: e,
            icon: "error",
          });
        }
      });
    },
    async getPdf(res) {
      const {data} = res
      if (data.isSign === "Y") {
        this.$store.commit("UPDATE_SIGN_STATUS", true);
      }
      this.model = 2
      this.url = data.pdfPath;
      this.getNumPages(data.pdfPath);
      this.showTopTips();
    },
    showTopTips() {
      if (this.isSign) {
        this.$refs.uTips.show({
          title: "签约成功",
          type: "success",
          duration: "230000",
        });
      }
    },
    goSign() {
      this.model = 3
    },
    //计算pdf页码总数
    getNumPages(url) {
      let loadingTask = ShowPdf.createLoadingTask(url);
      loadingTask.promise
          .then((pdf) => {
            this.numPages = pdf.numPages;
            setTimeout(() => {
              this.isShowLoading = false;
            }, 1500);
          })
          .catch((err) => {
            uni.showToast({
              title: "协议加载失败",
              icon: "error",
            });
          });
    },
    // 签名完成
    async onSignFinish(base64String) {
      const signPath = await this.uploadSignImg(base64String)
      await this.sign(signPath)
    },
    //上传签名
    async uploadSignImg(base64String) {
      const service = this.getAxiosService()

      //这里对base64串进行操作，去掉url头，并转换为byte
      let bytes = window.atob(base64String.split(",")[1]);
      let array = [];
      for (let i = 0; i < bytes.length; i++) {
        array.push(bytes.charCodeAt(i));
      }
      let blob = new Blob([new Uint8Array(array)], {type: "image/png"});
      let formData = new FormData();
      formData.append("file", blob, Date.now() + ".png");

      const response = await service({
        url: "/xsdcrm-wechat-api/common/upload",
        method: "POST",
        data: formData,
      })
      let res = response.data;
      if (res.code !== 200) {
        uni.showToast({
          title: res.msg,
          icon: "error",
        });
        return '';
      }
      return res.fileName
    },
    // 签署协议
    async sign(signPath) {
      uni.showLoading({
        title: "正在签署协议，请稍后···",
      });
      try {
        const service = this.getAxiosService()
        // 生成签署协议
        const fl = new FormData();
        fl.append("signPath", signPath);
        const res = await service({
          url: "/xsdcrm-wechat-api/riders/induction/insure_cancel/sign",
          method: "POST",
          data: fl,
        })
        uni.hideLoading();
        let {data} = res;
        let {code, msg} = data;
        if (code !== 200) {
          uni.showToast({
            title: msg,
            icon: "error",
          });
          return
        }
        uni.showToast({
          title: "协议签署成功！",
          icon: "success",
        });
        this.model = 2
        uni.navigateTo({
          url: `/pages/insure_cancel/preview?isSign=Y&pdfPath=${this.url}`
        })
      } catch (e) {
        uni.hideLoading()
        uni.showToast({
          title: e,
          icon: 'error'
        })
      }
    },
    getAxiosService() {
      const service = axios.create({
        baseURL: consts.API_BASE_URL,
        timeout: 1000 * 60 * 3,
        headers: {
          "Content-Type": "multipart/form-data",
        },
      });
      service.interceptors.request.use(
          (config) => {
            if (
                config.url.indexOf("withoutLogin") == -1 ||
                config.url.indexOf("bindAndLogin") == -1 ||
                config.url.indexOf("listDept") == -1
            ) {
              let token = uni.getStorageSync("token");
              token && token !== "" && (config.headers.Authorization = "Bearer " + token);
            }
            return config;
          },
          (error) => {
            return Promise.reject(error);
          }
      );
      return service
    }
  },
  // 必须要在onReady生命周期，因为onLoad生命周期组件可能尚未创建完毕
  onReady() {
    this.$refs.uForm.setRules(this.rules);
  },
};
</script>

<style lang="scss" scoped>
.container {
  box-sizing: border-box;
  padding: 20px;
}

.custom-btn {
  //margin: 15px auto;
  //left: 50%;
  //transform: translateX(-50%);
}

uni-page-body {
  height: 100%;
}

.u-tips {
  height: auto;
}

.pdf-box {
  position: absolute !important;
  top: 120px;
  height: 68vh;
  overflow-y: scroll;
}

.tips {
  position: absolute;
  bottom: 50px;
  margin: 15px auto;
  left: 50%;
  transform: translateX(-50%);
  width: 80%;
  font-size: 12px;
  color: #666;
  width: 100%;
  text-align: center;
}

.custom-btn {
  position: absolute;
  bottom: 10px;
  margin: 15px auto;
  left: 50%;
  transform: translateX(-50%);
}

.loading-box {
  position: fixed;
  left: 50%;
  top: 50%;
  transform: translate(-50%, -50%);
  text-align: center;

  .text {
    margin-top: 10px;
  }
}

.fixed {
  position: fixed;
  width: 100%;
  height: 90px;
  bottom: 0;
  background: #fff;
  border-top: 1px solid #e1e1e1;
}

.pt40 {
  padding-top: 50px;
}

.h80 {
  height: 73vh !important;
}
</style>
